package com.archie.zhufengfm.utils;

import android.os.Build;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;

/**
 * Created
 * Author: yuqi
 * Email：inconceivable_man@163.com
 * Date: 2015/10/12
 */

/**
 * Http 请求工具类
 */
public final class HttpTools {

    public static final String USER_AGENT = "ting_4.1.7(" + Build.MODEL + "," + Build.VERSION.SDK_INT + ")";

    private HttpTools() {

    }

    private static final int CONNECT_TIMEOUT = 5000;

    private static final int READ_TIMEOUT = 10000;

    public static byte[] doGet(String url) {
        byte[] ret = null;

        if (url != null) {

            HttpURLConnection conn = null;

            try {

                URL u = new URL(url);
                conn = (HttpURLConnection) u.openConnection();

                // 设置连接的配置
                conn.setConnectTimeout(CONNECT_TIMEOUT);
                conn.setReadTimeout(READ_TIMEOUT);

                conn.setRequestMethod("GET");

                // 完善 HTTP 请求的内容
                // 1. 设定通用的 Http 头信息

                // 设置 Accept 头信息，告诉服务器客户端能够接受什么样的数据
                //conn.setRequestProperty("Accept", "application/*, text/*, image/*,*/*");

                // 设置接受的内容压缩编码算法
                conn.setRequestProperty("Accept-Encoding", "gzip");

                // 设置 User-Agent
                conn.setRequestProperty("User-Agent", USER_AGENT);

                conn.connect();

                int code = conn.getResponseCode();
                if (code == 200) {

                    //TODO 给 data 赋值
                    InputStream in = null;

                    try {

                        in = conn.getInputStream();

                        // TODO 进行网络输入流的GZIP解压缩
                        String encoding = conn.getHeaderField("Content-Encoding");

                        if("gzip".equals(encoding)){

                            in = new GZIPInputStream(in);

                        }
                        ret = StreamUtil.readStream(in);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        StreamUtil.close(in);
                    }

                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                StreamUtil.close(conn);
            }

        }
        return ret;
    }
}
